package com.mask.demo;

import java.util.concurrent.*;

/**
 *
 * Create by hx
 * Date 2021/8/23 9:09 下午
 * 创建线程
 */

public class HowToCreateThread {
    static class  MyThread extends Thread{
        @Override
        public void run() {
            System.out.println("Hello Thread");
        }
    }

    static class MyRun implements Runnable{
        @Override
        public void run() {
            System.out.println("Hello Thread2");
        }
    }

    // 启动线程的5种方式
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new MyThread().start();
        new Thread(new MyRun()).start();

        new Thread(() -> {
            System.out.println("Hello Lambda!");
        }).start();

        FutureTask<String> task = new FutureTask<>(new MyCall());
        Thread t = new Thread(task);
        t.start();
        System.out.println("FutureTask:"+task.get());

        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(() -> {
            System.out.println("Hello ThreadPool");
        });

        // Future异步
        Future<String> f = service.submit(new MyCall());
        // f.get() 阻塞式
        String s = f.get();
        System.out.println("Future:"+s);
        service.shutdown();
    }

    private static class MyCall implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("Hello MyCall");
            return "success";
        }
    }
}

